﻿using System;
using System.Linq;
using Toast.Core.Interfaces;

namespace Toast.Core
{
    class ContentTypeResolver
    {
        public static IContent Discover(string from, InjectAt injectAt)
        {
            try
            {
                IContent result = null;

                AppDomain.CurrentDomain.GetAssemblies().ToList()
                    .SelectMany(s => s.GetTypes())
                    .Where(x => typeof(IContent).IsAssignableFrom(x) && x.IsPublic && !x.IsAbstract && !x.IsInterface)
                    .Select(type => ((IContent)Activator.CreateInstance(type)))
                    .Any(obj => obj.TryConstructFrom(from, out result));

                if (result != null)
                {
                    result.InjectAt = injectAt;
                    return result;
                }

                throw new Exception("Could not discover content type from given string. Either ammend the string or use an explicit content type.");
            }
            catch (MissingMemberException ex)
            {
                throw ex;
            }
            catch (Exception ex)
            {

                throw new Exception("ContentTypeResolver error while discovering type from given string, regex may need ammending");

            }

        }
    }
}